package com.huluobo.a2209mdmdemo.views

import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.lib_base.BaseTitle
import com.hyphenate.EMCallBack
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMGroup
import com.hyphenate.chat.EMGroupManager.EMGroupStyle
import com.hyphenate.chat.EMGroupOptions
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking


/**
 *  Created by LC on 2025/3/12.
 */
@Composable
fun CreateGroupPage(navHostController: NavHostController) {
    var groupName by remember {
        mutableStateOf("")
    }

    var groupDesc by remember {
        mutableStateOf("")
    }

    Column(
        Modifier
            .fillMaxWidth()
            .padding(20.dp),
        verticalArrangement = Arrangement.spacedBy(20.dp)
    ) {
        BaseTitle(title = "创建讨论组", navHostController = navHostController)
        OutlinedTextField(value = groupName, onValueChange = { groupName = it }, Modifier.fillMaxWidth(), label = {
            Text(text = "讨论组名字")
        })
        OutlinedTextField(value = groupDesc, onValueChange = { groupDesc = it }, Modifier.fillMaxWidth(), label = {
            Text(text = "讨论组描述")
        })
        Button(onClick = {
            val option = EMGroupOptions()
            option.maxUsers = 100
            option.style = EMGroupStyle.EMGroupStylePublicOpenJoin
            EMClient.getInstance().groupManager()
                .asyncCreateGroup(
                    groupName,
                    groupDesc,
                    arrayOf(EMClient.getInstance().currentUser),
                    "",
                    option,
                    object : EMValueCallBack<EMGroup> {
                        override fun onSuccess(value: EMGroup?) {
                            runBlocking(Dispatchers.Main) {
                                ToastUtils.showLong("创建群成功")
                                navHostController.popBackStack()
                            }
                        }

                        override fun onError(error: Int, errorMsg: String?) {
                            Log.i("TagA", "创建讨论组失败:$errorMsg,code:$error")
                        }
                    })
        }) {
            Text(text = "创建讨论组")
        }
    }
}